package com.wjj.sixinone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wjj.sixinone.common.enums.ExceptionEnum;
import com.wjj.sixinone.common.exception.GlobalException;
import com.wjj.sixinone.common.pojo.entity.User;
import com.wjj.sixinone.common.util.AuthContextUtil;
import com.wjj.sixinone.common.util.BaiduAiUtils;
import com.wjj.sixinone.common.util.Result;
import com.wjj.sixinone.service.FaceAiService;
import com.wjj.sixinone.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AIFaceServiceImpl implements FaceAiService {

    @Resource
    private BaiduAiUtils baiduAiUtils;
    @Autowired
    private UserService userService;

    //识别人脸
    public Result checkFace(StringBuffer imageBast64) {


        String image = imageBast64.substring(imageBast64.indexOf(",") + 1, imageBast64.length());
        String userId = baiduAiUtils.faceSearch(image);


        if(userId == null|| userId.equals(" ")) {
            throw new GlobalException(ExceptionEnum.FACE_ERROR);
        }
        String id = String.valueOf(AuthContextUtil.get().getId());
        if(!userId.equals(id)){
            throw new GlobalException(ExceptionEnum.FACE_ERROR);
        }
        return Result.ok();
    }

    //注册人脸
    public Result registerFace(StringBuffer imageBase64){


        // 注册用户编号  这里模拟用户登录行为  业务场景是当用户第一次通过手动输入密码并且成功登录以后，可以调用人脸识别采集信息，后面的登录可以使用人脸识别完成
        String image = imageBase64.substring(imageBase64.indexOf(",") + 1, imageBase64.length());   // 拆分图片数据，固定格式
        Integer id = AuthContextUtil.get().getId();
        User user =new User();
        user.setFaceRegister(id);




        Boolean isSuccess = baiduAiUtils.faceRegister(String.valueOf(id), image);                               // 调用百度官方utils工具包完成用户数据注册
        // {"result":{"face_token":"124da5c979b1faf9bb777e34c48b80fc","location":{"top":222.67,"left":181.69,"rotation":-1,"width":196,"height":190}},"log_id":1795978355,"error_msg":"SUCCESS","cached":0,"error_code":0,"timestamp":1721520178}
        System.out.println("注册状态 isSuccess=" + isSuccess);

        if (!isSuccess){
            throw new GlobalException(ExceptionEnum.FACE_REGISTER_ERROR);

        }
        userService.update(user,new LambdaQueryWrapper<User>().eq(User::getId,id));

        return Result.ok();
    }
}
